package cn.xi.controller;

import cn.xi.checkItem.MemberService;
import cn.xi.constant.MessageConstant;
import cn.xi.constant.RedisMessageConstant;
import cn.xi.entity.Result;
import cn.xi.pojo.Member;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/check")
    public Result check(HttpServletResponse response, @RequestBody Map map) {
        String validateCode = (String) map.get("validateCode");
        String telephone = (String) map.get("telephone");
        String s = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (!validateCode.equals(s)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        Member member = memberService.selectPhoneNumber(telephone);
        if (member == null) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.save(member);
        }
        //写入cookie
        Cookie cookie = new Cookie("membertelephone", telephone);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*30);
        response.addCookie(cookie);
        String s1 = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone,60*30,s1);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }
}
